<?php

namespace app\controller;

use app\BaseController;
use app\model\Archives;
use app\model\China;
use app\model\Parameter;
use app\model\User_character;

/**
 * 客户档案
 * Class ArchivesController
 * @package app\controller
 * @author 下雨吧จุ๊บ
 */
class ArchivesController extends BaseController
{

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {GET} /archives  客户档案列表
     * @apiDescription 客户档案列表
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: 客户档案列表,
     * message: '获取客户档案列表成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function index()
    {
        $data = input();
        if (empty($data['listRows'])) {
            $data['listRows'] = '8';
        }
        if (empty($data['page'])) {
            $data['page'] = '1';
        }
        $map[] = ['c.title', 'like', '%%'];
        if (!empty($data['map']['title'])) {
            $map[] = ['c.title', 'like', '%' . $data['map']['title'] . '%'];
        }
        if (!empty($data['map']['typeid'])) {
            $map[] = ['c.typeid', '=', $data['map']['typeid']];
        }
        if (!empty($data['map']['start_time'])) {
            $map[] = ['c.createtime', '>=', $data['map']['start_time']];
        }
        if (!empty($data['map']['end_time'])) {
            $map[] = ['c.createtime', '<=', $data['map']['end_time']];
        }
        if (!empty($data['map']['industryid'])) {
            $map[] = ['c.industryid', '=', $data['map']['industryid']];
        }
        if (!empty($data['map']['provinceid'])) {
            $map[] = ['c.provinceid', '=', $data['map']['provinceid']];
        }
        if (!empty($data['map']['start_time1'])) {
            $map[] = ['c.lasttime', '>=', $data['map']['start_time1']];
        }
        if (!empty($data['map']['end_time1'])) {
            $map[] = ['c.lasttime', '<=', $data['map']['end_time1']];
        }
        if (!empty($data['map']['tel'])) {
            $map[] = ['c.tel', 'like', '%' . $data['map']['tel'] . '%'];
        }
        if (!empty($data['map']['fromid'])) {
            $map[] = ['c.fromid', '=', $data['map']['fromid']];
        }
        if (!empty($data['map']['userid'])) {
            $map[] = ['c.userid', '=', $data['map']['userid']];
        }
        if (!empty($data['map']['categoryid'])){
            $map[] = ['c.categoryid','=',$data['map']['categoryid']];
        }
        if (!empty($data['map']['status'])){
            $map[] = ['c.status','=',$data['map']['status']];
        }
        //普通用户只能看到自己管理的档案
        $data['list'] = Archives::alias('c')
            ->join(['parameter' => 'p1'], 'p1.id=c.typeid')//客户类型
            ->join(['parameter' => 'p2'], 'p2.id=c.categoryid')//客户类别
            ->join(['parameter' => 'p3'], 'p3.id=c.fromid')//客户来源
            ->join(['parameter' => 'p4'], 'p4.id=c.industryid')//所属行业
            ->join(['user' => 'u1'], 'u1.id=c.userid')//员工
            ->join(['china' => 'ch1'], 'ch1.id=c.provinceid')//省份
            ->join(['china' => 'ch2'], 'ch2.id=c.cityid')//城市
            ->where('userid', cache($_SESSION['token']['value'])['id'])
            ->where($map)
            ->order('updatetime desc')
            ->field('c.*,p1.title as typetitle,p2.title as categorytitle,p3.title as fromtitle,p4.title as industrytitle,u1.realname as username,ch1.name as provincename,ch2.name as cityname')
            ->paginate([
                'list_rows' => $data['listRows'],
                'page' => $data['page'],
            ]);
        //超级管理员看到所有
        if (cache($_SESSION['token']['value'])['id'] == 1) {
            $data['list'] = Archives::alias('c')
                ->join(['parameter' => 'p1'], 'p1.id=c.typeid')//客户类型
                ->join(['parameter' => 'p2'], 'p2.id=c.categoryid')//客户类别
                ->join(['parameter' => 'p3'], 'p3.id=c.fromid')//客户来源
                ->join(['parameter' => 'p4'], 'p4.id=c.industryid')//所属行业
                ->join(['user' => 'u1'], 'u1.id=c.userid')//员工
                ->join(['china' => 'ch1'], 'ch1.id=c.provinceid')//省份
                ->join(['china' => 'ch2'], 'ch2.id=c.cityid')//城市
                ->where($map)
                ->order('updatetime desc')
                ->field('c.*,p1.title as typetitle,p2.title as categorytitle,p3.title as fromtitle,p4.title as industrytitle,u1.realname as username,ch1.name as provincename,ch2.name as cityname')
                ->paginate([
                    'list_rows' => $data['listRows'],
                    'page' => $data['page'],
                ]);
        }
        //获取客户类别
        $data['category'] = Parameter::where('status', 1)->where('pid', 92)->select();
        //获取客户类型
        $data['type'] = Parameter::where('status', 1)->where('pid', 91)->select();
        //获取客户行业
        $data['industry'] = Parameter::where('status', 1)->where('pid', 77)->select();
        //获取省份信息
        $data['province'] = China::where('level', 1)->select();
        //员工列表
        $data['user'] = \app\model\User::where('status', 1)->select();
        success($data, '客户档案列表获取成功');
    }

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {GET} /archives/create  新增
     * @apiDescription 新增线索界面
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: array,
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function create()
    {
        //获取客户类型
        $data['type'] = Parameter::where('status', 1)->where('pid', 91)->select();
        //获取客户类别
        $data['category'] = Parameter::where('status', 1)->where('pid', 92)->select();
        //获取客户来源
        $data['from'] = Parameter::where('status', 1)->where('pid', 79)->select();
        //获取客户行业
        $data['industry'] = Parameter::where('status', 1)->where('pid', 77)->select();
        //获取省份信息
        $data['province'] = China::where('level', 1)->select();
        //获取城市信息
        $data['city'] = '';
        //员工列表
        $data['user'] = \app\model\User::where('status', 1)->select();
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {POST} /archives  新增保存
     * @apiDescription 新增保存
     * @apiParam {String} title 客户名称(必填*)
     * @apiParam {String} tel 电话号码(必填*)
     * @apiParam {String} typeid 客户类型id(必填*)
     * @apiParam {String} categoryid 客户类别id(必填*)
     * @apiParam {String} fromid 客户来源id(必填*)
     * @apiParam {String} provinceid 省份id(必填*)
     * @apiParam {String} cityid 城市id(必填*)
     * @apiParam {String} industryid 所属行业id(必填*)
     * @apiParam {String} userid 分配员工id
     * @apiParam {String} authorid 录入人id(必填*)
     * @apiParam {String} link 网址
     * @apiParam {String} contacts 联系人
     * @apiParam {String} address 地址
     * @apiParam {String} firsttime 咨询日期
     * @apiParam {String} content 描述
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '新增成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function save()
    {
        $data = input();
        //必填项验证
        if (empty($data['title'])){
            error('请填写客户名称');
        }
        //重复验证
        $istitle = Archives::where('title',$data['title'])->find();
        if (!empty($istitle)){
            error('该名称已存在');
        }
        //必填项验证
        if (empty($data['contacts'])){
            error('请填写联系人');
        }
        //必填项验证
        if (empty($data['tel'])){
            error('请填写电话号码');
        }
        //必填项验证
        if (empty($data['firsttime'])){
            error('请填写资讯日期');
        }
        //必填项验证
        if (empty($data['userid'])) {
            $data['userid'] = cache($_SESSION['token']['value'])['id'];
        }
        //补充部门id
        $data['characterid'] = User_character::where('userid', $data['userid'])->find()['characterid'];
        //补充录入人id
        $data['authorid'] = cache($_SESSION['token']['value'])['id'];
        //补全信息
        $data['createtime'] = time();
        $data['updatetime'] = time();
        //添加数据
        $result = Archives::insert($data);
        if ($result) {
            success(array(), '添加成功');
        }
        error('添加失败');
    }

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {GET} /archives/:id  编辑读取查看
     * @apiDescription 编辑页面/查看页面(:id是指该条id,直接写在路由中)
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: array
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function read()
    {
        $data = input();
        //必填项验证
        if (empty($data['id'])) {
            error('520数据错误(Missing parameter id)');
        }
        //获取客户类型
        $data['type'] = Parameter::where('status', 1)->where('pid', 91)->select();
        //获取客户类别
        $data['category'] = Parameter::where('status', 1)->where('pid', 92)->select();
        //获取客户来源
        $data['from'] = Parameter::where('status', 1)->where('pid', 79)->select();
        //获取客户行业
        $data['industry'] = Parameter::where('status', 1)->where('pid', 77)->select();
        //获取省份信息
        $data['province'] = China::where('level', 1)->select();
        //员工列表
        $data['user'] = \app\model\User::where('status', 1)->select();
        //资讯线索详情
        $data['info'] = Archives::alias('i')
            ->join(['parameter' => 'p1'], 'p1.id=i.typeid')//客户类型
            ->join(['parameter' => 'p2'], 'p2.id=i.categoryid')//客户类别
            ->join(['parameter' => 'p3'], 'p3.id=i.fromid')//客户来源
            ->join(['parameter' => 'p4'], 'p4.id=i.industryid')//所属行业
            ->join(['user' => 'u1'], 'u1.id=i.userid')//员工
            ->join(['china' => 'ch1'], 'ch1.id=i.provinceid')//省份
            ->join(['china' => 'ch2'], 'ch2.id=i.cityid')//城市
            ->where('i.id', $data['id'])
            ->field('i.*,p1.title as typetitle,p2.title as categorytitle,p3.title as fromtitle,p4.title as industrytitle,u1.realname as username,ch1.name as provincename,ch2.name as cityname')
            ->find();
        //省份code
        $code = China::where('id', $data['info']['provinceid'])->find();
        if (!empty($code)) {
            //获取城市信息
            $data['city'] = China::where('pid', $code['code'])->select();
        }
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {PUT} /archives/:id  编辑保存
     * @apiDescription 编辑页面保存(:id是指该条id,直接写在路由中)
     * @apiParam {String} title 客户名称(必填*)
     * @apiParam {String} tel 电话号码(必填*)
     * @apiParam {String} typeid 客户类型id(必填*)
     * @apiParam {String} categoryid 客户类别id(必填*)
     * @apiParam {String} fromid 客户来源id(必填*)
     * @apiParam {String} provinceid 省份id(必填*)
     * @apiParam {String} cityid 城市id(必填*)
     * @apiParam {String} industryid 所属行业id(必填*)
     * @apiParam {String} userid 分配员工id
     * @apiParam {String} authorid 录入人id(必填*)
     * @apiParam {String} link 网址
     * @apiParam {String} contacts 联系人
     * @apiParam {String} address 地址
     * @apiParam {String} firsttime 咨询日期
     * @apiParam {String} content 描述
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '保存成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function update()
    {
        $data = input();
        //必填项验证
        if (empty($data['title'])){
            error('请填写客户名称');
        }
        //必填项验证
        if (empty($data['contacts'])){
            error('请填写联系人');
        }
        //必填项验证
        if (empty($data['tel'])){
            error('请填写电话号码');
        }
        //必填项验证
        if (empty($data['firsttime'])){
            error('请填写资讯日期');
        }
        //必填项验证
        if (empty($data['userid'])){
            $data['userid'] = 1;
        }
        //重复验证
        $info = Archives::where('id',$data['id'])->find();
        if ($info['title'] != $data['title']){
            $istitle = Archives::where('title',$data['title'])->find();
            if (!empty($istitle)){
                error('该名称已存在');
            }
        }
        //更新操作时间
        $data['updatetime'] = time();
        //更新数据
        $result = Archives::where('id', $data['id'])->save($data);
        success(array(), '保存成功');
    }

    /**
     * @apiGroup 客户档案
     * @apiVersion 1.0.0
     * @api {DELETE} /archives/0  删除
     * @apiDescription 删除(路由中直接写0,ids集合使用参数传递)
     * @apiParam {array} ids id集合
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '删除成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function delete()
    {
        $data = input();
        //必填项验证
        if (empty($data['ids'])) {
            error('请选择要删除的选项');
        }
        $result = Archives::whereIn('id', $data['ids'])->delete();
        success(array(), '删除成功');
    }
}
